package com.study.hadoop.weather;

import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.util.StringUtils;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @author stephen
 * @create 2019-01-10 20:57
 * @since 1.0.0
 */
public class WeatherMapper extends Mapper<LongWritable, Text,Weather, IntWritable> {

    Weather weather = new Weather();
    IntWritable temp = new IntWritable() ;

    @Override
    protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        // 1950-10-01 14:12:11  32c
        String[] splits = StringUtils.split(value.toString(), '\t');

        SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd") ;
        try {
            Date date = sdf.parse(splits[0]);
            Calendar cal = Calendar.getInstance();
            cal.setTime(date);

            weather.setYear(cal.get(Calendar.YEAR));
            weather.setMonth(cal.get(Calendar.MONTH));
            weather.setDay(cal.get(Calendar.DAY_OF_MONTH));

            int t = Integer.parseInt(splits[1].substring(0,splits[1].length()-1)) ;
            weather.setTemp(t);

            temp.set(t);

            context.write(weather,temp);

        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}
